package cc.admin.modules.message.handle.impl;

import cc.admin.common.constant.CommonConstant;
import cc.admin.common.constant.CommonSendStatus;
import cc.admin.common.constant.WebsocketConst;
import cc.admin.common.sys.vo.LoginUser;
import cc.admin.common.util.DySmsEnum;
import cc.admin.common.util.DySmsHelper;
import cc.admin.modules.message.handle.ISendMsg;
import cc.admin.modules.message.websocket.WebSocket;
import cc.admin.modules.sys.entity.SysAnnouncement;
import cc.admin.modules.sys.entity.SysUser;
import cc.admin.modules.sys.service.IShortMessagesService;
import cc.admin.modules.sys.service.ISysAnnouncementService;
import cc.admin.modules.sys.service.ISysUserService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SmsSendMsgHandle implements ISendMsg {

    @Autowired
    private ISysAnnouncementService sysAnnouncementService;

    @Resource
    private WebSocket webSocket;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    private IShortMessagesService shortMessagesService;

    @Override
    public void sendSms(String phones, JSONObject param, DySmsEnum dySmsEnum) {
        try {
            //循环发送短信给接收人
            List<String> phoneList = Arrays.stream(phones.split(",")).map(s -> s.trim()).collect(Collectors.toList());
            for (String phone : phoneList) {
                shortMessagesService.sendTextMessage(phone, param, dySmsEnum);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendMessage(String phones, String es_title, String es_contents, String moduleName, String busName) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //根据手机号查找用户
        String sql = String.format("select id,realname from sys_user where phone in (%s)", phones);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        List<String> userlist = new ArrayList<>();
        for (Map map : list) {
            userlist.add(map.get("id") + "");
        }
        String userId = CollectionUtil.join(userlist, ",");

        SysAnnouncement sysAnnouncement = new SysAnnouncement();
        sysAnnouncement.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
        //发布中
        sysAnnouncement.setSendStatus(CommonSendStatus.PUBLISHED_STATUS_PUBLISH);
        sysAnnouncement.setSendTime(new Date());
        sysAnnouncement.setSender(sysUser.getId());
        sysAnnouncement.setMsgType("assign");
        sysAnnouncement.setSenderName(sysUser.getRealname());
        sysAnnouncement.setStartTime(new Date());
        sysAnnouncement.setEndTime(new Date());
        sysAnnouncement.setUserIds(userId);
        sysAnnouncement.setTitle(es_title);
        sysAnnouncement.setMsgContent(es_contents);
        sysAnnouncement.setMsgType("assign");
        sysAnnouncement.setModuleName(moduleName);
        sysAnnouncement.setBusName(busName);
        sysAnnouncement.setPriority("L");
        sysAnnouncementService.saveAnnouncement(sysAnnouncement);

        String[] userIds = StrUtil.split(userId, ",");
        String anntId = sysAnnouncement.getId();
        Date refDate = new Date();
        JSONObject obj = new JSONObject();
        obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
        obj.put(WebsocketConst.MSG_ID, sysAnnouncement.getId());
        obj.put(WebsocketConst.MSG_TXT, JSONObject.toJSON(sysAnnouncement));
        webSocket.sendMoreMessage(userIds, obj.toJSONString());


    }

    @Override
    public void timedSendMessage(String phones, String es_title, String es_contents, String moduleName, String busName) {
        //根据手机号查找用户
        String sql = String.format("select id,realname from sys_user where phone in (%s)", phones);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        List<String> userlist = new ArrayList<>();
        for (Map map : list) {
            userlist.add(map.get("id") + "");
        }
        String userId = CollectionUtil.join(userlist, ",");

        SysAnnouncement sysAnnouncement = new SysAnnouncement();
        sysAnnouncement.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
        //发布中
        sysAnnouncement.setSendStatus(CommonSendStatus.PUBLISHED_STATUS_PUBLISH);
        sysAnnouncement.setSendTime(new Date());
        sysAnnouncement.setMsgType("assign");
        sysAnnouncement.setSenderName("定时任务");
        sysAnnouncement.setStartTime(new Date());
        sysAnnouncement.setEndTime(new Date());
        sysAnnouncement.setUserIds(userId);
        sysAnnouncement.setTitle(es_title);
        sysAnnouncement.setMsgContent(es_contents);
        sysAnnouncement.setMsgType("assign");
        sysAnnouncement.setPriority("L");
        sysAnnouncement.setModuleName(moduleName);
        sysAnnouncement.setBusName(busName);

        sysAnnouncementService.saveAnnouncement(sysAnnouncement);

        String[] userIds = StrUtil.split(userId, ",");
        String anntId = sysAnnouncement.getId();
        Date refDate = new Date();
        JSONObject obj = new JSONObject();
        obj.put(WebsocketConst.MSG_CMD, WebsocketConst.CMD_USER);
        obj.put(WebsocketConst.MSG_ID, sysAnnouncement.getId());
        obj.put(WebsocketConst.MSG_TXT, JSONObject.toJSON(sysAnnouncement));
        webSocket.sendMoreMessage(userIds, obj.toJSONString());
    }


    @Override
    public void send(String title, SysUser user, JSONObject mobj, String message, DySmsEnum code, Map<String, Object> map) {
        SysAnnouncement sysAnnouncement = new SysAnnouncement();
        String objId = IdUtil.objectId();
        sysAnnouncement.setId(objId);
        sysAnnouncement.setTitle(title);
        sysAnnouncement.setMsgContent(message);
        sysAnnouncement.setPriority("L");
        sysAnnouncement.setMsgCategory("notice");
        sysAnnouncement.setMsgType("assign");
        sysAnnouncement.setUserIds(user.getId());
        sysAnnouncement.setModuleName(String.valueOf(map.get("moduleName")));
        sysAnnouncement.setBusName(String.valueOf(map.get("busName")));
        if (map.get("fileId") != null) {
            sysAnnouncement.setFileId(String.valueOf(map.get("fileId")));
        }

        sysAnnouncement.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
        //未发布
        sysAnnouncement.setSendStatus(CommonSendStatus.PUBLISHED_STATUS_PUBLISH);
        sysAnnouncement.setSendTime(new Date());
        sysAnnouncement.setSenderName("定时任务");
        sysAnnouncementService.saveAnnouncement(sysAnnouncement);

        //发布
        sysAnnouncementService.popupMessage(sysAnnouncement);
        //发送短信
        shortMessagesService.sendTextMessage(user.getPhone(), mobj, code);
    }

}
